import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPClientServer {
    //声明用于与服务端通讯的Socket对象
    private Socket socket;
    //输入服务端的IP 端口号 创建Socket对象

    public TCPClientServer(String serverIP,int serverPort) throws IOException {
        if(serverIP == null || serverIP.isEmpty()) {
            throw new BindException("IP不可为空");
        }
        if(serverPort < 1024 || serverPort > 65535) {
            throw new BindException("端口号异常..");
        }
        this.socket = new Socket(serverIP,serverPort);
    }
    //启动客户端
    public void start() {
        System.out.println("客户端已启动...");

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //循环处理数据
            while (true) {
                System.out.print("->");
                Scanner scanner = new Scanner(System.in);
                String request = scanner.nextLine();
                //非空检验
                if(request == null || request.isEmpty()) {
                    System.out.println("输入不可为空..");
                    continue;
                }
                //使用print Writer简化输出
                PrintWriter printWriter = new PrintWriter(outputStream);
                //传输给服务端
                printWriter.println(request);
                //刷新缓存区
                printWriter.flush();
                //用Scanner简化服务端输入的数据
                Scanner scanner1 = new Scanner(inputStream);
                //解析响应数据
                String response = scanner1.nextLine();
                //打印日志
                System.out.printf("request = %s,response = %s\n",request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPClientServer tcpClientServer = new TCPClientServer("192.168.31.175",5555);
        tcpClientServer.start();
    }
}
